<template>
  <!-- 左侧导航菜单 -->
  <el-aside class="app-sidebar">
    <div class="sidebar-content">
      <!-- 自定义菜单列表 -->
      <div class="custom-menu">
        <!-- 动态生成菜单项 -->
        <div v-for="menuItem in menuItems" :key="menuItem.path" class="menu-group">
          <!-- 主菜单项 -->
          <div class="menu-item" :class="{
            'active': isActive(menuItem.path),
            'has-children': menuItem.children && menuItem.children.length > 0,
            'expanded': expandedMenus.includes(menuItem.path)
          }" @click="handleMenuClick(menuItem)">
            <span class="menu-title">{{ menuItem.title }}</span>
            <div class="menu-icons">
              <!-- 展开/收起箭头 (只有子菜单才显示) -->
              <el-icon v-if="menuItem.children && menuItem.children.length > 0" class="expand-arrow"
                :class="{ 'expanded': expandedMenus.includes(menuItem.path) }">
                <ArrowDown />
              </el-icon>
              <!-- 菜单图标 -->
              <el-icon class="menu-icon">
                <component :is="menuItem.icon" />
              </el-icon>
            </div>
          </div>

          <!-- 子菜单项 (带动画) -->
          <transition name="submenu">
            <div v-if="menuItem.children && menuItem.children.length > 0 && expandedMenus.includes(menuItem.path)"
              class="submenu-container">
              <div v-for="child in menuItem.children" :key="child.path" class="submenu-group">
                <!-- 二级菜单项 -->
                <div class="submenu-item" :class="{
                  'active': isActive(child.path),
                  'has-children': child.children && child.children.length > 0,
                  'expanded': expandedMenus.includes(child.path)
                }" @click="handleSubMenuClick(child)">
                  <span class="submenu-title">{{ child.title }}</span>
                  <div class="submenu-icons">
                    <!-- 三级菜单展开箭头 -->
                    <el-icon v-if="child.children && child.children.length > 0" class="expand-arrow"
                      :class="{ 'expanded': expandedMenus.includes(child.path) }">
                      <ArrowDown />
                    </el-icon>
                    <!-- 二级菜单图标 -->
                    <el-icon class="submenu-icon">
                      <component :is="child.icon" />
                    </el-icon>
                  </div>
                </div>

                <!-- 三级菜单项 (带动画) -->
                <transition name="submenu">
                  <div v-if="child.children && child.children.length > 0 && expandedMenus.includes(child.path)"
                    class="third-level-container">
                    <div v-for="grandChild in child.children" :key="grandChild.path" class="third-level-item"
                      :class="{ 'active': isActive(grandChild.path) }" @click="handleThirdLevelClick(grandChild)">
                      <span class="third-level-title">{{ grandChild.title }}</span>
                      <el-icon class="third-level-icon">
                        <component :is="grandChild.icon" />
                      </el-icon>
                    </div>
                  </div>
                </transition>
              </div>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </el-aside>
</template>

<script setup>
// 导入Vue组合式API
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 获取路由和路由器实例
const route = useRoute()
const router = useRouter()

// 展开的菜单项
const expandedMenus = ref([])

// 从路由配置中生成菜单项
const menuItems = computed(() => {
  // 获取所有路由
  const routes = router.getRoutes()

  // 过滤出需要在菜单中显示的主路由
  const mainRoutes = routes.filter(route => {
    // 检查是否为主路由的条件：
    // 1. 有showInMenu标记
    // 2. 没有父路由
    // 3. 路径中只有一个斜杠（排除子路由）
    const hasMenuFlag = route.meta?.menu?.showInMenu
    const hasNoParent = !route.parent
    const isTopLevel = route.path.split('/').length === 2 && route.path !== '/'

    return hasMenuFlag && hasNoParent && isTopLevel
  })

  // 构建菜单项
  const menuRoutes = mainRoutes.map(route => {
    // 构建子菜单数据（从route.children获取）
    const children = route.children ? route.children
      .filter(childRoute => childRoute.meta?.menu?.showInMenu)
      .map(childRoute => {
        // 构建二级菜单的完整路径
        const childFullPath = childRoute.path.startsWith('/') ? childRoute.path : route.path + '/' + childRoute.path

        // 构建三级菜单数据（优先从真实路由children获取，其次从meta获取）
        const thirdLevelChildren = childRoute.children ? childRoute.children
          .filter(grandChildRoute => grandChildRoute.meta?.menu?.showInMenu)
          .map(grandChildRoute => {
            // 构建三级菜单的完整路径
            const grandChildFullPath = grandChildRoute.path.startsWith('/')
              ? grandChildRoute.path
              : childFullPath + '/' + grandChildRoute.path

            return {
              path: grandChildFullPath,
              title: grandChildRoute.meta.menu.title,
              icon: grandChildRoute.meta.menu.icon,
              order: grandChildRoute.meta.menu.order || 999
            }
          })
          .sort((a, b) => a.order - b.order) : (childRoute.meta.menu.children || [])

        return {
          path: childFullPath,
          title: childRoute.meta.menu.title,
          icon: childRoute.meta.menu.icon,
          order: childRoute.meta.menu.order || 999,
          children: thirdLevelChildren
        }
      })
      .sort((a, b) => a.order - b.order) : []

    return {
      path: route.path,
      title: route.meta.menu.title,
      icon: route.meta.menu.icon,
      order: route.meta.menu.order || 999,
      children: children
    }
  }).sort((a, b) => a.order - b.order)

  return menuRoutes
})

// 判断菜单项是否激活
const isActive = (path) => {
  return route.path === path || route.path.startsWith(path + '/')
}

// 处理主菜单点击
const handleMenuClick = (menuItem) => {
  // console.log('点击菜单:', menuItem)

  // 如果有子菜单，切换展开状态
  if (menuItem.children && menuItem.children.length > 0) {
    const index = expandedMenus.value.indexOf(menuItem.path)
    if (index > -1) {
      expandedMenus.value.splice(index, 1)
    } else {
      expandedMenus.value.push(menuItem.path)
    }
  } else {
    // 没有子菜单，直接跳转
    if (menuItem.path !== route.path) {
      router.push(menuItem.path).catch(err => {
        console.log('路由跳转失败:', err)
      })
    }
  }
}

// 子菜单点击
const handleSubMenuClick = (child) => {
  // console.log('点击子菜单:', child)

  // 如果有三级菜单，切换展开状态
  if (child.children && child.children.length > 0) {
    const index = expandedMenus.value.indexOf(child.path)
    if (index > -1) {
      expandedMenus.value.splice(index, 1)
    } else {
      expandedMenus.value.push(child.path)
    }
  } else {
    // 没有三级菜单，直接跳转
    if (child.path !== route.path) {
      router.push(child.path).catch(err => {
        console.log('路由跳转失败:', err)
      })
    }
  }
}

// 处理三级菜单点击
const handleThirdLevelClick = (grandChild) => {
  // console.log('点击三级菜单:', grandChild)
  if (grandChild.path !== route.path) {
    router.push(grandChild.path).catch(err => {
      console.log('路由跳转失败:', err)
    })
  }
}

// 初始化展开状态 - 如果当前路由在某个子菜单下，自动展开父菜单
const initExpandedMenus = () => {
  menuItems.value.forEach(menuItem => {
    if (menuItem.children && menuItem.children.length > 0) {
      // 检查二级菜单是否有激活的项
      const hasActiveChild = menuItem.children.some(child => isActive(child.path))
      if (hasActiveChild && !expandedMenus.value.includes(menuItem.path)) {
        expandedMenus.value.push(menuItem.path)
      }

      // 检查三级菜单是否有激活的项
      menuItem.children.forEach(child => {
        if (child.children && child.children.length > 0) {
          const hasActiveGrandChild = child.children.some(grandChild => isActive(grandChild.path))
          if (hasActiveGrandChild) {
            // 展开父菜单
            if (!expandedMenus.value.includes(menuItem.path)) {
              expandedMenus.value.push(menuItem.path)
            }
            // 展开子菜单
            if (!expandedMenus.value.includes(child.path)) {
              expandedMenus.value.push(child.path)
            }
          }
        }
      })
    }
  })
}

// 监听路由变化，更新展开状态
watch(() => route.path, () => {
  initExpandedMenus()
}, { immediate: true })
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.app-sidebar {
  width: 300px;
  height: calc(100vh - 80px);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.sidebar-content {
  height: 100%;
  width: 260px;
  background: rgba(50, 46, 62, 0.9);
  border-radius: 10px;
  border: 1px solid #2E2D3C;
  overflow-y: auto;
}

.custom-menu {
  width: 100%;

  .menu-group {
    .menu-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 14px 20px;
      background-color: rgba(230, 230, 230, 0.1);
      box-shadow: 0px 1px 0px 0px #43425A;
      color: #FFF;
      cursor: pointer;
      transition: all 0.3s ease;
      font-size: 20px;
      font-weight: 500;

      &:hover {
        background-color: #485670;
        color: #ffffff;
      }

      &.active {
        background-color: #c85a54;
        color: #ffffff;

        .menu-icons .menu-icon {
          color: #ffffff;
        }
      }

      .menu-title {
        flex: 1;
        text-align: left;
        user-select: none;
      }

      .menu-icons {
        display: flex;
        align-items: center;
        gap: 8px;

        .expand-arrow {
          font-size: 14px;
          color: #a8b3c5;
          transition: transform 0.3s ease;

          &.expanded {
            transform: rotate(180deg);
          }
        }

        .menu-icon {
          font-size: 18px;
          color: #a8b3c5;
        }
      }

      &.has-children.expanded {
        .menu-icons .expand-arrow {
          color: #ffffff;
        }
      }
    }

    .submenu-container {
      background-color: rgba(32, 31, 47, 0.7);

      .submenu-group {
        .submenu-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 14px 20px 14px 10px;
          color: #FFF;
          cursor: pointer;
          transition: all 0.3s ease;
          font-size: 18px;
          border-left: 3px solid transparent;
          box-shadow: 0px 1px 0px 0px #43425A;

          &:hover {
            background-color: #3c4b64;
            color: #ffffff;
          }

          &.active {

            border-left-color: #E34234;
            background-color: rgba(227, 66, 52, 0.3);
            color: #E34234;

            .submenu-icons .submenu-icon {
              color: #E34234;
            }
          }

          .submenu-title {
            flex: 1;
            text-align: left;
            user-select: none;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .submenu-icons {
            display: flex;
            align-items: center;
            gap: 6px;

            .expand-arrow {
              font-size: 12px;
              color: #8a96a8;
              transition: transform 0.3s ease;

              &.expanded {
                transform: rotate(180deg);
              }
            }

            .submenu-icon {
              font-size: 16px;
              color: #8a96a8;
            }
          }

          &.has-children.expanded {
            .submenu-icons .expand-arrow {
              color: #ffffff;
            }
          }

          &::before {
            content: '•';
            margin-right: 8px;
            color: #8a96a8;
          }

          &.active::before {
            color: #E34234;
          }
        }

        .third-level-container {
          background-color: #1B1A2A;

          .third-level-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 14px 20px 14px 40px;
            color: #FFF;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 18px;
            border-left: 3px solid transparent;
            box-shadow: 0px 1px 0px 0px #43425A;

            &:hover {
              background-color: #2e3a4f;
              color: #ffffff;
            }

            &.active {
              border-left-color: #E34234;
              background-color: rgba(227, 66, 52, 0.2);
              color: #E34234;

              .submenu-icons .submenu-icon {
                color: #E34234;
              }
            }

            .third-level-title {
              flex: 1;
              text-align: left;
              user-select: none;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .third-level-icon {
              font-size: 14px;
              color: #E34234;
            }

            &::before {
              content: '•';
              margin-right: 8px;
              color: #E34234;
            }

            &.active::before {
              color: #E34234;
            }
          }
        }
      }
    }
  }
}

// 子菜单展开/收起动画
.submenu-enter-active,
.submenu-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.submenu-enter-from,
.submenu-leave-to {
  max-height: 0;
  opacity: 0;
}

.submenu-enter-to,
.submenu-leave-from {
  max-height: 500px;
  opacity: 1;
}

// 滚动条样式
.app-sidebar::-webkit-scrollbar {
  width: 6px;
}

.app-sidebar::-webkit-scrollbar-track {
  background: #2e3a4f;
}

.app-sidebar::-webkit-scrollbar-thumb {
  background: #485670;
  border-radius: 3px;
}

.app-sidebar::-webkit-scrollbar-thumb:hover {
  background: #5a6b7d;
}
</style>
